<?php
if(!defined("YUEXUAN_REAL_ROOT_PATH")){
	exit("Access Denied.");
}

/**
 * 基类
 * @author tongjun
 *
 */
class base {
	private $memcache = null;
	private $kvdb = null;
	private $db = null;
	private $logger = null;
	public $openID = null;
	
	public function __construct($openID=null) {
		if($openID){
			$this->openID = $openID;
		}
	}
	
	/**
	 * 取得数据库连接
	 * @return mysql
	 */
	protected function db($dbServer){
		if(!$this->db){
			$this->db = ext_dbHandle::getDb($dbServer);
		}
		return $this->db;
	}
	
	/**
	 * 取得memcache连接
	 * @return memcache
	 */
	protected function memcache(){
		if(!$this->memcache){
			$this->memcache = ext_memcacheHandle::getInstance();
		}
		return $this->memcache;
	}
	
	/**
	 * 取得kvdb连接
	 * @return kvdb
	 */
	protected function kvdb(){
		if(!$this->kvdb){
			$this->kvdb = ext_kvdb::getInstance();
		}
		return $this->kvdb;
	}
	
	/**
	 * 取得logger实例
	 * @return ext_logger
	 */
	protected function logger(){
		if(!$this->logger){
			$this->logger = ext_logger::getInstance();
		}
		return $this->logger;
	}
	
	/**
	 * 取得当前客户端的IP
	 * @return string
	 */
	protected function getIp(){
		if(!empty($_SERVER["HTTP_CLIENT_IP"])){
			$cip = $_SERVER["HTTP_CLIENT_IP"];
		}else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
			$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}else if(!empty($_SERVER["REMOTE_ADDR"])){
			$cip = $_SERVER["REMOTE_ADDR"];
		}else{
			$cip = '';
		}
	       preg_match("/[\d\.]{7,15}/", $cip, $cips);
	       $cip = isset($cips[0]) ? $cips[0] : 'unknown';
	       unset($cips);
	       return $cip;
	}
	
	// 二维数组排序
	function array_sort($arr,$keys,$type='asc'){
		$keysvalue = $new_array = array();
		foreach ($arr as $k=>$v){
			$keysvalue[$k] = $v[$keys];
		}
		if($type == 'asc'){
			asort($keysvalue);
		}else{
			arsort($keysvalue);
		}
		reset($keysvalue);
		foreach ($keysvalue as $k=>$v){
			$new_array[$k] = $arr[$k];
		}
		return $new_array;
	}
}
